package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/google/uuid"
	"log"
	"math/rand"
	"micro/api/params"
	"micro/gobal"
	"micro/inits"
	"micro/model"
	"micro/pkg"
	"net/http"
	"strconv"
	"time"
)

func Login(c *gin.Context) {

	req := params.UserReq{}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	sprintf := fmt.Sprintf("短信%v", req.Mobile)
	result, _ := gobal.Rdb.Get(inits.Ctx, sprintf).Result()
	if result != req.Code {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "短信验证码错误",
		})
	}

	var user model.User

	gobal.DB.Debug().Where("mobile=?", user.Mobile).Find(&user)

	token, err := pkg.GetToken(strconv.Itoa(int(user.ID)))
	if err != nil {
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": token,
	})

}

func Sms(c *gin.Context) {
	sms := params.SendSms{}
	if err := c.ShouldBind(&sms); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	code := rand.Intn(900000) + 100000
	_, err := pkg.SendSms(sms.Mobile, strconv.Itoa(code))
	if err != nil {
		return
	}
	sprintf := fmt.Sprintf("短信%v", sms.Mobile)
	gobal.Rdb.Set(inits.Ctx, sprintf, code, time.Minute*3)
	//if *sendSms.Body.Code != "OK" {
	//	c.JSON(http.StatusBadRequest, gin.H{
	//		"code": 400,
	//		"msg":  *sendSms.Body.Message,
	//		"data": nil,
	//	})
	//}
	//c.JSON(http.StatusOK, gin.H{
	//	"code": 200,
	//	"msg":  "短信发送成功",
	//})
}

func Register(c *gin.Context) {

	res := params.UserReq{}
	if err := c.ShouldBind(&res); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	sprintf := fmt.Sprintf("短信%v", res.Mobile)
	result, _ := gobal.Rdb.Get(inits.Ctx, sprintf).Result()
	if result != res.Code {
		c.JSON(http.StatusBadRequest, gin.H{
			"code": 400,
			"msg":  "短信验证码错误",
		})
	}

	user := model.User{

		Mobile:   res.Mobile,
		Password: pkg.Md5(res.Password),
	}
	gobal.DB.Debug().Create(&user)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

func Upload(c *gin.Context) {

	file, _ := c.FormFile("file")
	log.Println(file.Filename)

	filename := uuid.NewString() + ".jpg"
	// 上传文件至指定的完整文件路径
	c.SaveUploadedFile(file, "./upload/"+filename)

	//rootDir, _ := os.Getwd()

}
